package com.movies.controller;

import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.gridfs.GridFSDBFile;
import com.movies.model.Movie;
import com.movies.repository.MongoRepository;
import com.movies.repository.MovieMapper;
import com.movies.vo.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/rest/movie")
public class MovieController {
    private static final Logger logger = LoggerFactory.getLogger(HomeController.class);

    @Autowired
    private MovieMapper movieMapper;

    @Autowired
    private MongoRepository mongoRepository;

    @RequestMapping(value = "/addMovie")
    public Response saveMovie(Movie movie, @RequestParam MultipartFile post) throws IOException {
        String postId = "";
        try {
            postId = mongoRepository.saveFile(post.getInputStream(), post.getOriginalFilename(), post.getContentType(), null);
            movie.setPostId(postId);
            movieMapper.saveMovie(movie);
            return new Response(true);
        } catch (Exception e) {
            if(null!=mongoRepository.findById(postId)){
                mongoRepository.deleteById(postId);
            }
            return new Response(false);

        }
    }

    @RequestMapping(value = "/editMovie")
    public Response updateMovie(@RequestBody Movie movie) {
        movieMapper.updateMovie(movie);
        return new Response(true);
    }

    @RequestMapping("/getAllMovies")
    public List<Movie> getAllMovies() {
        return movieMapper.findAllMovies();
    }

    @RequestMapping("/deleteMovie/{id}")
    public Response deleteMovie(@PathVariable("id") Integer id) {
        int row = movieMapper.deleteMovie(id);
        if (0 == row) {
            Response response = new Response(false);
            response.getHeader().setResultMessage("不存在该电影");
            return response;
        }
        return new Response(true);
    }

    @RequestMapping("/upload")
    public Response uploadPicture(@RequestParam MultipartFile file) throws IOException {
        DBObject metaData = new BasicDBObject();
        mongoRepository.saveFile(file.getInputStream(), "test", file.getContentType(), metaData);
        return new Response(true);
    }

    @RequestMapping("/download/{id}")
    public Response downloadPicture(@PathVariable("id") String id, HttpServletResponse response) throws IOException {
        List<GridFSDBFile> files = mongoRepository.findAll();
        if (!CollectionUtils.isEmpty(files)) {
            for (GridFSDBFile file : files) {
                response.setHeader("content-disposition", "attachment;filename=" + file.getFilename());
                file.writeTo(response.getOutputStream());
            }
        }
        return new Response(true);
    }

    @RequestMapping("/down/{name}")
    public Response downloadPictureByName(@PathVariable("name") String name, HttpServletResponse response) throws IOException {
        GridFSDBFile file = mongoRepository.find(name);

        if (null == file) {
            Response responsevo = new Response(false);
            responsevo.getHeader().setResultMessage("没有该图片");
            return responsevo;
        }
        response.setHeader("content-disposition", "attachment;filename=" + file.getFilename());
        file.writeTo(response.getOutputStream());

        return new Response(true);
    }
}
